<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="客户名称" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入客户名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商机名称" prop="businessName">
        <el-input
          v-model="queryParams.businessName"
          placeholder="请输入商机名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="businessList" @selection-change="handleSelectionChange" ref="tb">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商机名称" align="center" prop="businessName">
        <template slot-scope="scope">
          <el-link @click="showBusDetail(scope.row)" style="color:#1890ff">{{scope.row.businessName}}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="客户名称" align="center" prop="customerName">
        <template slot-scope="scope">
          <el-link @click="showCustomerDetail(scope.row)" style="color:#1890ff">{{scope.row.customerName}}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="销售阶段" align="center" prop="statusName" />
      <el-table-column label="商机级别" align="center" prop="busLevel"  :formatter="busLevelFormat"/>
      <el-table-column label="首要联系人" align="center" prop="firstContacts" />
      <el-table-column label="预计成交日期" align="center" prop="dealDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.dealDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商机金额(元)" align="center" prop="money" />
      <el-table-column label="负责人" align="center" prop="businessLeader" />
      <el-table-column label="商机状态" align="center" prop="isEnd" :formatter="isEndFormat" />
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商机对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span = "12">
            <el-form-item label="商机名称" prop="businessName">
              <el-input v-model="form.businessName" placeholder="请输入商机名称" />
            </el-form-item>
          </el-col>
          <el-col :span = "12">
            <el-form-item label="客户名称" prop="customerName">
              <el-input placeholder="请选择客户名称" v-model="form.customerName" @blur = "isWrite" @input="onInput()">
                <el-button slot="append" icon="el-icon-search" @click="selCustomer"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="描述" prop="busMsg">
          <el-input v-model="form.busMsg" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-row>
          <el-col :span = "12">
            <el-form-item label="商机来源" prop="busSource">
              <el-input v-model="form.busSource" placeholder="请输入商机来源"  @input="onInput1()"/>
            </el-form-item>
          </el-col>
          <el-col :span = "12">
            <el-form-item label="商机金额(元)" prop="money">
              <el-input-number v-model="form.money" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span = "12">
            <el-form-item label="整单折扣" prop="discountRate">
              <el-input-number v-model="form.discountRate" controls-position="right" :min="0" />%
            </el-form-item>
          </el-col>
          <el-col :span = "12">
            <el-form-item label="首要联系人" prop="firstContacts">
              <el-input v-model="form.firstContacts" placeholder="请输入首要联系人" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span = "12">
            <el-form-item label="电话" prop="firstTel">
              <el-input v-model="form.firstTel" placeholder="请输入电话" />
            </el-form-item>
          </el-col>
          <el-col :span = "12">
            <el-form-item label="邮箱" prop="first_mail">
              <el-input v-model="form.firstMail" placeholder="请输入首要联系人" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span = "12">
            <el-form-item label="预计成交日期" prop="dealDate">
              <el-date-picker clearable size="small"
                v-model="form.dealDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择预计成交日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span = "12">
            <el-form-item label="负责人" prop="businessLeader">
              <el-select v-model="form.businessLeader" placeholder="请选择负责人" filterable  @change="onInput2()">
                <el-option label="请选择负责人" value="" />
                <el-option
                  v-for="dict1 in businessLeaders"
                  :key="dict1.userId"
                  :label="dict1.nickName"
                  :value="dict1.userId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span = "12">
            <el-form-item label="阶段分类" prop="typeId">
              <el-select v-model="form.typeId" placeholder="请选择阶段分类" @change="typeSelChange">
                <el-option label="请选择阶段分类" value="" />
                <el-option
                  v-for="dict in typeIds"
                  :key="dict.ids"
                  :label="dict.name"
                  :value="dict.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span = "12">
            <el-form-item label="销售阶段" prop="statusId">
              <el-select v-model="form.statusId" placeholder="请选择阶段">
                <el-option label="请选择阶段" value="" />
                <el-option
                  v-for="dict in statusIds"
                  :key="dict.id"
                  :label="dict.name"
                  :value="dict.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span = "12">
            <el-form-item label="商机级别" prop="leader">
              <el-select v-model="form.busLevel" placeholder="请选择客户级别"  @change="onInput3()">
                <el-option label="全部" value="" />
                <el-option
                  v-for="dict in busLevels"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span = "12">
            <el-form-item label="商机状态" prop="isEnd">
              <el-select v-model="form.isEnd" placeholder="请选择商机状态" clearable size="small">
                <el-option
                  v-for="dict in isEndOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="状态说明" prop="statusRemark">
          <el-input v-model="form.statusRemark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="附件" prop="annex">
          <fileUpload v-model="form.annex"/>
        </el-form-item>
      </el-form>


      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 右侧弹出详情信息 -->
    <el-drawer
      title="商机跟踪"
      :visible.sync="bus_drawer"
      :direction="direction"
      :modal = false
      size = "70%"
      :before-close="handleClose">
      <followUp :busId='this.businessId'></followUp>
    </el-drawer>

    <!-- 右侧弹出详情信息 -->
    <el-drawer
      title="客户跟踪"
      :visible.sync="customer_drawer"
      :direction="direction"
      :modal = false
      size = "70%"
      :before-close="handleClose">
      <customerFllowUp :customerId='this.customerId'></customerFllowUp>
    </el-drawer>

    <!-- 选择客户对话框 -->
    <el-dialog :title="selCusTitle" :visible.sync="selCusOpen" width="50%" append-to-body>
      <busCustomers @selCusCancel = "selCusCancel" @getCustomerInfo = "getCustomerInfo" :isNewTime = "this.isNewTime"></busCustomers>
    </el-dialog>


    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="selBusOk">确 定</el-button>
      <el-button @click="conCusCancel">取 消</el-button>
    </div>

  </div>
</template>

<script>
import { listBusiness, getBusiness, delBusiness, addBusiness, updateBusiness, exportBusiness } from "@/api/crm/business/business";
import { getAllListType, getType } from "@/api/crm/busstage/type";
import { listadmin } from "@/api/system/user";
import followUp from './followUp'
import customerFllowUp from '../customer/followUp'
import FileUpload from '@/components/FileUpload';
import busCustomers from '../customer/bus_customers'

export default {
  props: {
      //获取随机数，每次选择客户都重新刷新查询页面
      isNewTime: {},
  },
  name: "contractBus",
  components: {
    followUp,
    customerFllowUp,
    FileUpload,
    busCustomers
  },
  data() {
    return {
      selCusTitle: "",
      selCusOpen: false,
      // 遮罩层
      loading: true,
      direction: 'rtl',
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商机表格数据
      businessList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 商机状态字典
      isEndOptions: [],
      //商机级别
      busLevels: [],
      //商机阶段分类
      typeIds: [],
      //商机阶段
      statusIds: [],
      //选择的客户信息
      selCustomerInfo: {},
      //负责人
      businessLeaders: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        typeId: null,
        statusId: null,
        customerId: null,
        businessName: null,
        businessLeader: null,
        isEnd: null,
      },
      // 表单参数
      form: {},
      //客户信息右侧弹出框
      customer_drawer: false,
      //商机信息右侧弹出框
      bus_drawer: false,
      //客户id
      customerId: "",
      //商机id
      businessId: "",
      //选择的商机
      selBusiness: {},
      // 表单校验
      rules: {
        businessName: [
          { required: true, message: "商机名称不能为空", trigger: "blur" }
        ],
        typeId: [
          { required: true, message: "商机阶段分类不能为空", trigger: "blur" }
        ],
        statusId: [
          { required: true, message: "商机阶段不能为空", trigger: "blur" }
        ],
        businessLeader: [
          { required: true, message: "负责人不能为空", trigger: "blur" }
        ],
        isEnd: [
          { required: true, message: "商机状态", trigger: "blur" }
        ],
        firstContacts: [
          { required: true, message: "首要联系人", trigger: "blur" }
        ],
        firstTel: [
          { required: true, message: "首要联系人电话", trigger: "blur" }
        ],
        firstMail: [
          { required: true, message: "首要联系人邮箱", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("business_type").then(response => {
      this.isEndOptions = response.data;
    });
    this.getDicts("clue_level").then(response => {
      this.busLevels = response.data;
    });
    getAllListType().then(response => {
      this.typeIds = response.data;
    })
    listadmin().then(response => {
      this.businessLeaders = response.data;
    });
  },
  methods: {
    //确认选择的商机
    selBusOk(){
      if(null == this.selBusiness){
        this.msgError("请选择商机信息");
        return;
      }else{
        this.$emit('getSelBusinessInfo', this.selBusiness);
      }
    },
    //选择客户对话框取消按钮
    selCusCancel1(){
      this.$emit('selCusCancel');
    },
    //选择商机对话框取消按钮
    conCusCancel(){
      this.$emit('conCusCancel');
    },
    onInput(){
      this.$forceUpdate();
    },
    onInput1(){
      this.$forceUpdate();
    },
    onInput2(){
      this.$forceUpdate();
    },
    onInput3(){
      this.$forceUpdate();
    },
    //判断是否新建写入客户
    isWrite(){
      if(this.form.customerId == null){
        return;
      }else{
        if(this.form.customerName != this.selCustomerInfo.customerName){
          this.form.customerId = null;
        }
      }
    },
    // 商机级别字典翻译
    busLevelFormat(row, column) {
      return this.selectDictLabel(this.busLevels, row.busLevel);
    },
    //选中客户后处理逻辑
    getCustomerInfo(selection){
      this.selCustomerInfo = selection;
      this.form.customerId = selection.id;
      this.form.customerName = selection.customerName;
      this.form.busSource = "客户 - " + selection.customerSource;
      this.form.businessLeader = selection.leader;
      this.form.busLevel = selection.customerLevel;
      this.form.firstContacts = selection.customerPerson;
      this.form.firstTel = selection.tel;
      this.form.firstMail = selection.mail;
      this.selCusOpen = false;
    },
    //选择客户对话框取消按钮
    selCusCancel(){
      this.selCusOpen = false;
    },
    //选择客户
    selCustomer(){
      this.isNewTime = new Date() + Math.round(Math.random()*50000);
      this.selCusTitle = "选择客户";
      this.selCusOpen = true;
    },
    //根据阶段分类id获取所有阶段
    typeSelChange(){
      getType(this.form.typeId).then(response => {
        this.statusIds = response.data.crmBusinessStatusList;
      });
    },
    //商机信息右侧弹出层
    showBusDetail(row){
      const id = row.id;
      this.businessId = id;
      this.bus_drawer = true;
    },
    //客户信息右侧弹出层
    showCustomerDetail(row){
      const id = row.customerId;
      this.customerId = id;
      this.customer_drawer = true;
    },
    //右侧弹出层关闭
    handleClose(done) {
      this.getList();
//      this.$confirm('确认关闭？')
//       .then(_ => {
          done();
//        }).catch(_ => {});
    },
    /** 查询商机列表 */
    getList() {
      this.loading = true;
      this.queryParams.isEnd = 0;//只查询进行中的商机
      listBusiness(this.queryParams).then(response => {
        this.businessList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 商机状态字典翻译
    isEndFormat(row, column) {
      return this.selectDictLabel(this.isEndOptions, row.isEnd);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.selCustomerInfo = {};
      this.form = {
        id: null,
        typeId: null,
        statusId: null,
        nextTime: null,
        customerId: null,
        firstContacts: null,
        firstTel: null,
        firstMail: null,
        dealDate: null,
        businessName: null,
        money: null,
        discountRate: null,
        totalPrice: null,
        businessLeader: null,
        batchId: null,
        roUserId: null,
        rwUserId: null,
        isEnd: null,
        statusRemark: null,
        status: 0,
        lastTime: null,
        followup: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        annex: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selBusiness = selection[0];
      if (selection.length > 1) {
        this.$refs.tb.clearSelection();
        this.$refs.tb.toggleRowSelection(selection.pop());
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商机";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getType(row.typeId).then(response => {
        this.statusIds = response.data.crmBusinessStatusList;
      });
      const id = row.id || this.ids
      getBusiness(id).then(response => {
        this.form = response.data;
        this.form.isEnd = "" + this.form.isEnd;
        this.open = true;
        this.title = "修改商机";
      });
    },
    /** 提交按钮 */
    submitForm() {
      let sel = this;
      if(this.form.customerId == null){
        this.$confirm('确定新增客户?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          sel.submitFormSave();
        })   
      }else{
        this.submitFormSave();
      }
           
    },
    submitFormSave(){
      this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateBusiness(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addBusiness(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除商机编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delBusiness(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有商机数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportBusiness(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    }
  },
    watch: {
        //新增
        isNewTime: {
        　　handler(newValue, oldValue) {
        　　    this.getList();
        　　},
            deep: true,
        　　immediate: true
        }
    } 
};
</script>
